﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Common;
using WindowsHelper;
using System.IO;

namespace SBarNonAdmin
{
    public partial class Form1 : Form
    {
        public static OperatingSystemVersion sv = new OperatingSystemVersion();
        public Form1()
        {
            InitializeComponent();
            uMsgNotify = WindowsAPI.RegisterWindowMessageA("SHELLHOOK");

            // This basically registers our window to receive the shell events

            if (!WindowsAPI.RegisterShellHookWindow(this.Handle))
                throw new Win32Exception(Marshal.GetLastWin32Error());
            // Instantiate our GlobalHooks objec
            if (sv.OSVersion == OSVersion.Vista)
            {
//                Timer StartPowerHook = new Timer();
//                StartPowerHook.Interval = 30000;
//                StartPowerHook.Enabled = true;
//                StartPowerHook.Tick += new EventHandler(StartPowerHook_Tick);
//                StartPowerHook.Start();
                //                RegisterForPowerNotifications(this.Handle); 
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GlobalHooksTest.frmSbarDevelopper.StartNewInstance(@"C:\Windows\Notepad.exe");
        }
        private IntPtr hPowerSrc = IntPtr.Zero;
        private IntPtr hBattCapacity = IntPtr.Zero;
        private IntPtr hMonitorOn = IntPtr.Zero;
        private IntPtr hPowerScheme = IntPtr.Zero;
        public void RegisterForPowerNotifications(IntPtr hwnd)
        {
            hPowerSrc = WindowsAPI.RegisterPowerSettingNotification(hwnd,
            ref WindowsAPI.GUID_ACDC_POWER_SOURCE,
            WindowsAPI.DEVICE_NOTIFY_WINDOW_HANDLE);

            hBattCapacity = WindowsAPI.RegisterPowerSettingNotification(hwnd,
            ref WindowsAPI.GUID_BATTERY_PERCENTAGE_REMAINING,
            WindowsAPI.DEVICE_NOTIFY_WINDOW_HANDLE);

            hMonitorOn = WindowsAPI.RegisterPowerSettingNotification(hwnd,
            ref WindowsAPI.GUID_MONITOR_POWER_ON,
            WindowsAPI.DEVICE_NOTIFY_WINDOW_HANDLE);

            hPowerScheme = WindowsAPI.RegisterPowerSettingNotification(hwnd,
            ref WindowsAPI.GUID_POWERSCHEME_PERSONALITY,
            WindowsAPI.DEVICE_NOTIFY_WINDOW_HANDLE);
        }
        private void UnregisterForPowerNotifications()
        {
            WindowsAPI.UnregisterPowerSettingNotification(hBattCapacity);
            WindowsAPI.UnregisterPowerSettingNotification(hMonitorOn);
            WindowsAPI.UnregisterPowerSettingNotification(hPowerScheme);
            WindowsAPI.UnregisterPowerSettingNotification(hPowerSrc);
        }
        static bool onBattery;
        enum PowerPersonality
        {
            Savings,
            Performance,
            Mixed
        };
        static PowerPersonality personality;
        private UInt32 uMsgNotify;

        public void ShellWindowCreated (IntPtr Handle)
        {
            string s = "";
                   try
                    {

                        s = Path.GetFileName(WindowsAPI.GetWindowModuleFileName(Handle)).ToLower();
//                        cv = treeListView1.GetItemAt(s);
                    }
                    catch
                    {
                        s = "";
//                        cv = null;
                    } 
            GlobalHooksTest.frmSbarDevelopper.ShellWindowCreated(Handle,s);
        }
        public void Flash_Window(IntPtr Handle)
        {
        }
        public void ShellWindowActivated(IntPtr Handle)
        {
        }
        public void ShellWindowDestroyed(IntPtr Handle)
        {
        }
        public void MinMax(IntPtr Handle)
        {
        }

        protected override void WndProc(ref Message m)
        {
            // Check to see if we've received any Windows messages telling us about our hooks
            if (m.Msg == Convert.ToInt32(uMsgNotify))
            {

                switch ((WindowsAPI.ShellEvents)m.WParam)
                {

                    //                    case ShellEvents.HSHELL_WINDOWCREATED:
                    //
                    //                        L1.Text = m.LParam.ToString();//this is the handle to the window created
                    //
                    //                        break;
                    case WindowsAPI.ShellEvents.HSHELL_FLASH:
                        Flash_Window((IntPtr)m.LParam);
                        break;
                    case WindowsAPI.ShellEvents.HSHELL_WINDOWACTIVATED:
                        ShellWindowActivated((IntPtr)m.LParam);
                        break;
                    case WindowsAPI.ShellEvents.HSHELL_WINDOWCREATED:
                        ShellWindowCreated((IntPtr)m.LParam);
                        break;
                    case WindowsAPI.ShellEvents.HSHELL_WINDOWDESTROYED:
                        ShellWindowDestroyed((IntPtr)m.LParam);
                        break;
                    case WindowsAPI.ShellEvents.HSHELL_GETMINRECT:
                        MinMax((IntPtr)m.LParam);
                        break;

                }

            }
            if (sv.OSVersion == OSVersion.Vista)
            {
                if (m.Msg == WindowsAPI.WM_POWERBROADCAST && m.WParam.ToInt32() == WindowsAPI.PBT_POWERSETTINGCHANGE)
                {
                    // Extract data from message
                    WindowsAPI.POWERBROADCAST_SETTING ps =
                        (WindowsAPI.POWERBROADCAST_SETTING)Marshal.PtrToStructure(
                                                                m.LParam, typeof(WindowsAPI.POWERBROADCAST_SETTING));
                    IntPtr pData = (IntPtr)(m.LParam.ToInt32() + Marshal.SizeOf(ps));

                    // Examine notification

                    if (ps.PowerSetting == WindowsAPI.GUID_POWERSCHEME_PERSONALITY &&
                        ps.DataLength == Marshal.SizeOf(typeof(Guid)))
                    {
                        // New power scheme selected.

                        Guid newPersonality =
                            (Guid)Marshal.PtrToStructure(pData, typeof(Guid));

                        if (newPersonality == WindowsAPI.GUID_MAX_POWER_SAVINGS)
                        {
                            personality = PowerPersonality.Savings;
                        }
                        else if (newPersonality == WindowsAPI.GUID_MIN_POWER_SAVINGS)
                        {
                            personality = PowerPersonality.Performance;
                        }
                        else if (newPersonality == WindowsAPI.GUID_TYPICAL_POWER_SAVINGS)
                        {
                            personality = PowerPersonality.Mixed;
                        }
                        else
                        {
                            Debug.WriteLine("switched to unknown Power savings");
                            personality = PowerPersonality.Mixed;
                        }
                    }
                    else if (ps.PowerSetting == WindowsAPI.GUID_ACDC_POWER_SOURCE &&
                             ps.DataLength == Marshal.SizeOf(typeof(Int32)))
                    {
                        Int32 iData = (Int32)Marshal.PtrToStructure(pData, typeof(Int32));
                        Debug.WriteLine("ACDC: " + iData);

                        onBattery = iData != 0;
                    }
                }
            }
            //            if (m.msg == WindowsAPI.WndMsg.WM_POWERBROADCAST)
            //            {
            //                
            //            }

            base.WndProc(ref m);
        }
    }
}
